#ifndef BACKUP_H
#define BACKUP_H
#include <QString>
#include <QFileInfo>
#include <QFile>
#include <QNetworkRequest>

#include <QHttpMultiPart>
#include <QNetworkReply>
#include <QEventLoop>
#include <QDir>
#include "datamanage.hpp"
#include "HttpManage.h"
#include <QThread>
#include "Global.h"
#include <QFileSystemWatcher>
class Backup
{
#define SERVER_ADDR "1.94.222.114"
#define SERVER_PORT 9090
public:
    Backup(const QString& backup_dir, const QString& backup_file) :
        _backup_dir(backup_dir)
    {
        QFile file(backup_file);
        if (!file.exists())
        {
            if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
                file.close();
            }
        }
        _data = new DataManager(backup_file);
    }
    ~Backup()
    {
        delete _data;
    }
    QString GetFileIdentifier(const QString& filename)
    {
        QFileInfo fileInfo(filename);
        QString identifier = QString("%1-%2-%3").arg(fileInfo.fileName()).arg(fileInfo.size()).arg(fileInfo.lastModified().toSecsSinceEpoch());
        return identifier;
    }

    bool Upload(const QString& filename)
    {
        QFile file(filename);
        if (!file.open(QIODevice::ReadOnly))
        {
            return false;
        }
        QByteArray body = file.readAll();
        file.close();
        QUrl url(gate_url_prefix+"/upload");
        QFileInfo fileInfo(filename);
        // 构建header
        QString pureName = fileInfo.fileName();
        qDebug() << "上传文件名：" << pureName;
        QString header = QString("form-data; name=\"file\"; filename=\"%1\"").arg(pureName);
        //HttpManage::GetInstance()->PostHttpMultiPartReq(url,header,body,ReqId::UPLOAD_FILE,Modules::FILEUPLOADMOD);
        // 修改为触发信号（子线程 -> 主线程）
        qDebug() << "触发上传请求：" << fileInfo.fileName();
        emit HttpManage::GetInstance()->uploadRequested(url, header, body, ReqId::UPLOAD_FILE, Modules::FILEUPLOADMOD);
        return true;
    }

    bool IsNeedUpload(const QString& filename)
    {
        QString identifier;
        if (_data->GetOneByFileName(filename, &identifier))
        {
            QString new_identifier = GetFileIdentifier(filename);
            if (new_identifier == identifier)
            {
                return false;
            }
        }
        QFileInfo fileInfo(filename);
        if (QDateTime::currentSecsSinceEpoch() - fileInfo.lastModified().toSecsSinceEpoch() < 5)
        {
            return false;
        }
        qDebug() << filename << "need upload!";
        return true;
    }

    bool RunModule()
    {
        qDebug() << "监控目录：" << _backup_dir;
        qDebug() << "监控初始化完成";
        qDebug() << "开始检查文件变动，目录：" << _backup_dir;
        while(true)
        {
            CheckAndUploadFiles();
            QThread::sleep(1);
        }
        return true;
    }
    void CheckAndUploadFiles()
    {
        QDir dir(_backup_dir);
        if (!dir.exists())
        {
            qDebug() << "路径无效或不可访问：" << dir.path();
        }
        QStringList arr = dir.entryList(QDir::Files);
        for (const QString& a : arr)
        {
            QString filePath = _backup_dir + QDir::separator() + a;
            if (!IsNeedUpload(filePath))
            {
                continue;
            }
            if (Upload(filePath))
            {
                QString identifier = GetFileIdentifier(filePath);
                _data->Insert(filePath, identifier);
                qDebug() << filePath << "upload success!";
            }
        }
    }
    void setBackupDir(QString backupDir)
    {
        if(_data != nullptr)
        {
            delete _data; // 释放旧的指针
        }
        _backup_dir = backupDir;
        _data = new DataManager(_backup_dir + "/backup.dat"); // 创建新数据管理器
        _watcher.removePath(_backup_dir);
        RunModule(); // 重新初始化监控
    }

private:
    QString _backup_dir;
    DataManager* _data;
    QFileSystemWatcher _watcher;
};
#endif // BACKUP_H
